<template>
  <div>
    <el-dialog
      v-model="dialogTableVisible"
      title="财务信息修改"
      top="2vh"
      @close="this.$refs.financeInfo.resetFields();this.currentTotal = 0"
    >
      <el-form
        :model="financeInfo"
        :label-width="80"
        label-position="left"
        ref="financeInfo"
        :rules="rules"
      >
        <el-form-item label="所属项目" prop="projectId">
          <el-select
            v-model="financeInfo.projectId"
            style="width: 100%"
            @change="getCurrentTotal"
          >
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="财务类型" prop="financeType">
          <el-radio
            v-model="financeInfo.financeType"
            label="入账"
            size="large"
            border
            >入账</el-radio
          >
          <el-radio
            v-model="financeInfo.financeType"
            label="支出"
            size="large"
            border
            >支出</el-radio
          >
        </el-form-item>
        <el-form-item label="金额" prop="financeTotal">
          <el-input
            type="text"
            v-model.number="financeInfo.financeTotal"
            placeholder="请输入金额"
          />
        </el-form-item>
        <el-form-item label="发生时间" prop="accurrentTime">
          <el-date-picker
            style="width: 100%"
            v-model="financeInfo.accurrentTime"
            type="date"
            placeholder="请选择发生时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="otherText">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            v-model="financeInfo.otherText"
            placeholder="请添加备注"
          />
        </el-form-item>

        <el-form-item label="添加附件" prop="file">
          <el-upload
            class="upload-demo"
            :before-remove="beforeRemove"
            :on-change="fileChangeFunc"
            drag
            action=""
            multiple
            name="file"
            style="float: left"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-icon class="el-icon--upload"><Document /></el-icon>
            <div class="el-upload__text">拖放文件上传 或 <em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                单个文件最大为50MB,总上传大小为100MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-tooltip
            effect="dark"
            content="结果不计入项目总余额中,可撤销与更改"
            placement="top"
          >
          <el-button type="primary" @click="theUpLoadType(1)">保存</el-button>
          </el-tooltip>

          <el-tooltip
            effect="dark"
            content="结果计入项目总金额,且操作不可逆"
            placement="top"
          >
          <el-button type="warning" @click="theUpLoadType(0)">提交</el-button>
          </el-tooltip>
          
          
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import axios from "../../utils/request";
import { Document } from "@element-plus/icons";
import { ElNotification } from "element-plus";
export default {
  components: { Document },
  inject: ["reload"],
  data() {
    return {
      dialogTableVisible: false,
      financeInfo: {},
      fileList: [],
      files: [],
      rules: {
        projectId: [
          { required: true, message: "该字段不允许为空", trigger: "blur" },
        ],
        financeType: [
          { required: true, message: "该字段不允许为空", trigger: "blur" },
        ],
        financeTotal: [
          {
            required: true,
            validator: this.checkFinanceTotal,
            trigger: "blur",
          },
          {
            min: 0,
            type: "number",
            message: "请输入大于0的数字",
            trigger: "blur",
          },
        ],
        accurrentTime: [
          {
            required: true,
            validator: this.checkAccurentTime,
            trigger: "blur",
          },
        ]
      },
      currentTotal:0,
    };
  },
  methods: {
    getFinanceInfoDetail(id) {
      let self = this;
      axios.get("/financeInfos/detail", { params: { id, id } }).then((res) => {
        self.financeInfo = res.data.data.financeInfo;
        this.getCurrentTotal();
        // console.log(res);
        for (var i = 0; i < res.data.data.financeInfo.files.length; i++) {
          this.fileList.push({
            id: res.data.data.financeInfo.files[i].id,
            name: res.data.data.financeInfo.files[i].utilSrcName,
            isExcite: true, //服务器中是否存在
          });
        }
      });
    },
    showDialog(id) {
      this.dialogTableVisible = true;
      this.getFinanceInfoDetail(id);
    },
    /**
     * 表单文件上传函数
     */
    beforeRemove(file, fileList) {
      console.log(fileList);
      // var re = this.$confirm(`确定将文件 ${file.name}从服务器中删除?`);
      if (file.isExcite === true) {
        axios
          .get("/UtilFiles/delete", { params: { id: file.id } })
          .then((res) => {
            ElNotification.success("文件" + res.data.message);
          });
      } else {
        //删除上传列表中数据
        this.files.splice(this.files.indexOf(file), 1);
      }
    },
    fileChangeFunc(file, fileList) {
      // console.log("file :",file);
      this.files.push(file);
      //   console.log("fileList:", fileList);
    },
    updateFunc() {
      this.$refs.financeInfo.validate((valid) => {
        if (valid) {
          var formData = new window.FormData();
          formData.append(
            "financeInfo",
            new Blob([JSON.stringify(this.financeInfo)], {
              type: "application/json",
            })
          );
          if (this.files.length != 0) {
            this.files.forEach((data) => {
              formData.append("files", data.raw);
            });
          }
          axios.post("/financeInfos/upData", formData).then((res) => {
            if (res.data.status === 200) {
              ElNotification({
                message: res.data.message,
                type: "success",
                duration: "1500",
              });
            }
            this.reload();
          });
        } else {
          return false;
        }
      });
    },
    /**
      获取项目列表
     */
    getProjectList() {
      axios.get("/ProjectInfo/projectList").then((res) => {
        this.projectList = res.data.data.projectList;
      });
    },
    /**
     * 表单发生时间校验
     */
    checkAccurentTime(rule, value, callback) {
      if (value == null || value == "") {
        callback(new Error("该字段不允许为空"));
      } else {
        let nowDate = new Date();
        let valDate = new Date(value);
        if (nowDate < valDate) {
          callback(new Error("时间不允许大于当前时间"));
        } else {
          callback();
        }
      }
    },

    /**
     * 项目余额字段校验
     */
    checkFinanceTotal(rule, value, callback) {
      if (value == null || value == "") {
        callback(new Error("该字段不允许为空"));
      } else if (
        this.financeInfo.financeType == "支出" &&
        value > this.currentTotal
      ) {
        callback(new Error("金额不允许大于该项目剩余金额"));
      } else {
        callback();
      }
    },

    /**
     * 下拉框改变事件
     */
    getCurrentTotal() {
      let _this = this;
      //获取当前项目余额
      axios
        .get("/ProjectInfo/remainPrice", {
          params: { id: this.financeInfo.projectId },
        })
        .then((res) => {
          _this.currentTotal = res.data.data.remainPrice;
        });
    },

    /**
     * 上传类型判断
     */
    theUpLoadType(typeId) {
      this.financeInfo.currentStatus = typeId;
      this.updateFunc();
    },
  },
  mounted() {
    this.getProjectList();
  },
};
</script>